import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'

import { Like, Repository } from 'typeorm'

import { paginate } from '~/helper/paginate'
import { Pagination } from '~/helper/paginate/pagination'
import { DictDataEntity } from '~/modules/system/dict-data/dict-data.entity'

import { DictDataQueryDto, DictDataSaveDto } from './dict-data.dto'

@Injectable()
export class DictDataService {
  constructor(
    @InjectRepository(DictDataEntity)
    private dictDataRepository: Repository<DictDataEntity>,
  ) {}

  /**
   * 罗列所有字典数据
   */
  async page({
    page,
    pageSize,
    label,
    value,
    dictType,
  }: DictDataQueryDto): Promise<Pagination<DictDataEntity>> {
    const queryBuilder = this.dictDataRepository.createQueryBuilder('dict_data').orderBy({ sort: 'ASC' }).where({
      ...(label && { label: Like(`%${label}%`) }),
      ...(value && { value: Like(`%${value}%`) }),
      ...(dictType && { dictType: Like(`%${dictType}%`) }),
    })

    return paginate(queryBuilder, { page, pageSize })
  }

  /**
   * 获取字典数据列表（不分页）
   */
  async list({
    label,
    value,
    dictType,
  }: DictDataQueryDto): Promise<DictDataEntity[]> {
    return this.dictDataRepository.find({
      where: {
        ...(label && { label: Like(`%${label}%`) }),
        ...(value && { value: Like(`%${value}%`) }),
        ...(dictType && { dictType: Like(`%${dictType}%`) }),
      },
      order: { sort: 'ASC' },
    })
  }

  /**
   * 根据字典类型获取字典数据列表
   */
  async getByDictType(dictType: string): Promise<DictDataEntity[]> {
    return this.dictDataRepository.find({
      where: {
        dictType,
        status: 0, // 只返回正常状态的数据
      },
      order: { sort: 'ASC' },
    })
  }

  /**
   * 获取字典数据总数
   */
  async countDictDataList(): Promise<number> {
    return this.dictDataRepository.count()
  }

  /**
   * 新增
   */
  async create(dto: DictDataSaveDto): Promise<void> {
    await this.dictDataRepository.insert(dto)
  }

  /**
   * 更新
   */
  async update(id: number, dto: Partial<DictDataSaveDto>): Promise<void> {
    await this.dictDataRepository.update(id, dto)
  }

  /**
   * 删除
   */
  async delete(id: number): Promise<void> {
    await this.dictDataRepository.delete(id)
  }

  /**
   * 查询单个
   */
  async findOne(id: number): Promise<DictDataEntity> {
    return this.dictDataRepository.findOneBy({ id })
  }
}
